package zpe.genericcrud.jsf.view.validator;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import org.springframework.util.StringUtils;

@FacesValidator("emailValidator") 
public class EmailValidator implements Validator{

	@Override
	public void validate(FacesContext arg0, UIComponent arg1, Object arg2)
		throws ValidatorException {
		if( !StringUtils.hasText( arg2.toString() ) ){
			String email = arg2.toString();
			boolean emailValido = false;
			if( email.indexOf( "@" ) > 0 && email.indexOf( "@" ) < ( email.length() - 1 ) ){
				emailValido = true;
			}

			if( !emailValido ){
				FacesMessage message = new FacesMessage( FacesMessage.SEVERITY_ERROR, "Email inválido.", "Email inválido." );
				throw new ValidatorException(message);
			}
		}
	}

}
